using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Globalization;

namespace Lizk.SimpleHUD
{
#if !XBOX
    public class GeometryConverter : ExpandableObjectConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(SizeS))
                return true;
            else if (destinationType == typeof(PointS))
                return true;
            else if (destinationType == typeof(RectangleS))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (value is PointS && destinationType == typeof(string))
            {
                PointS p = (PointS)value;
                
                return p.X + "; " + p.Y;
            }
            else if (value is SizeS && destinationType == typeof(string))
            {
                SizeS p = (SizeS)value;

                return p.Width + "; " + p.Height;
            }
            else if (value is RectangleS && destinationType == typeof(string))
            {
                RectangleS p = (RectangleS)value;
                return p.X + "; " + p.Y + "; " + p.Width + "; " + p.Height;
            }

            
            return base.ConvertTo(context, culture, value, destinationType);
        }


        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                try
                {
                    string s = (string)value;
                    string[] parts = s.Split(';');
                    if(parts.Length == 2)
                        return new PointS(Single.Parse(parts[0]), Single.Parse(parts[1]));
                    else if (parts.Length == 4)
                        return new RectangleS(Single.Parse(parts[0]), Single.Parse(parts[1]), Single.Parse(parts[2]), Single.Parse(parts[3]));
                    else throw new Exception();
                   


                }
                catch
                {
                    throw new ArgumentException(
                        "Can not convert '" + (string)value +
                                           "' to type GeometryObject");
                }
            } 
            
            return base.ConvertFrom(context, culture, value);
        }

    }
#endif
}
